import Axios from "axios"; // Axios
import Vue from "vue";
import store from "@/store";
import router from "@/router";

import ElementUI, { Loading } from "element-ui";
const _ = require("lodash");
import { formatObjectUndefined } from "./index.js";

// 全局配置
// Axios.defaults.baseURL = SETTING.api;
Axios.defaults.baseURL = "";

// Axios interceptor
let loadingInstance;
Axios.interceptors.request.use(
  config => {
    if (!config.dropLoading) {
      loadingInstance = Loading.service({
        fullscreen: true,
        spinner: "el-icon-loading",
        background: "rgba(255,255,255,0)",
        text: config.msg || Vue.prototype.LANG.common.loading_text
      });
    }

    if (config.data && typeof config.data === "string") {
      config.url += `?${config.data}`;
      config.data = {};
    } else if (!config.data) config.data = {};

    config.withCredentials = true;
    config.headers["X-Requested-With"] = +new Date();

    /* 全局参数 */
    if (!config.noGlobalParams) {
      const userInfo = store.state.user.userInfo || {};
      config.data.token = userInfo.token; // token
      config.data.userId = userInfo.userId; // 用户代码
      // config.headers["token"] = userInfo.token; // token
      // config.data[SETTING.operatorId] = userInfo.user_code; // 用户代码
    }

    /* 附加请求头 */
    if (config.addtionHeader) {
      for (let key in config.addtionHeader) {
        config.headers[key] = config.addtionHeader[key];
      }
    }

    /* 参数undefined转空String */
    // config.data = formatObjectUndefined(config.data);
    // const test = {
    //   a: 1, b: undefined, c: { c1: "c1", c2: undefined },
    //   d: [{ d1: "d1", d2: undefined }]
    // };
    // console.log("========================");
    // console.log(formatObjectUndefined(test));

    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// Axios interceptor
/** 拦截配置
 * code === 450：token过期
 */
Axios.interceptors.response.use(
  response => {
    let configData;
    try {
      configData = response.config.data && JSON.parse(response.config.data);
    } catch (e) {
      // console.log(e);
    }


    /* 统一处理接口返回 */
    if (response.data.code == 10000) {
      response.data.success = true;
      if (response.data.tips) {
        Vue.prototype.$mtMessage.success(response.data.tips);
      }
    } else {
      if (!(configData && configData.dropMessage)) {
        // Vue.prototype.$mtMessage.error(response.data.msg);
      }

      switch (response.data.code) {
        case 450: // token过期
          Vue.prototype.$mtMessage.error("当前账号过长时间未操作，请重新登录！");
          router.push("/login");
          break;
        case 1008:
          Vue.prototype.$mtMessage.error(Vue.prototype.LANG.common.unlogin);
          router.push("/login");
          break;
        case 20001: // 超时登出
          store.dispatch("user/logout");
          router.push("/login");
          break;
        default:
          break;
      }
    }

    if (loadingInstance) {
      setTimeout(() => {
        loadingInstance.close();
      }, 400);
    }
    return response.data;
  },
  error => {
    // 服务器错误
    if (loadingInstance) loadingInstance.close();
    Vue.prototype.$mtMessage.error(Vue.prototype.LANG.common.network_error);
    return Promise.reject(error);
  }
);

export default Axios;
